package com.cheer.ba.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.app.oss.UploadPicManager;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.presenter.impl.OilMealPresenter;
import com.cheer.ba.utils.CacheUtils;
import com.cheer.ba.utils.ImageUtils;
import com.cheer.ba.utils.LogUtils;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.widget.ShowPopupView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 描述 ：投诉建议
 * 作者 ：hq
 * 时间 ：2017/5/23 14:44
 */
public class SuggestAty extends BaseCommAty implements ShowPopupView.OnItemPopupClick {

    @BindView(R.id.id_root_view)
    RelativeLayout mLinearRoot;

    //标题
    @BindView(R.id.id_input_title_edit)
    EditText mEditTitle;
    private String mSaveTitle;
    //内容
    @BindView(R.id.id_input_content_edit)
    EditText mEditContent;
    private String mSaveContent;

    @BindView(R.id.id_photo_img)
    ImageView mImgPic;

    //弹出头像框
    private ShowPopupView popupView;
    public static final String[] POPUP_ITEMS = {"拍摄", "从相册上传"};
    //记录拍照 0 拍照 1 相册
    private int mRecordIndex;
    //记录相片的绝对路径
    private String mPhotoFileName;
    private File mPhotoFile;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String path = (String) msg.obj;
                    /**
                     * 保存图片
                     */
                    ((OilMealPresenter) presenter).mySuggest(mSaveTitle, mSaveContent, path);
                    break;
            }
        }
    };

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_suggest, null, false));
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }


    @Override
    public void initPresenter() {
        presenter = new OilMealPresenter();
        ((OilMealPresenter) presenter).setmUpLoadPicManager();
    }

    @Override
    public void initView() {
        setTitleText(getString(R.string.mine_ask_question));
        popupView = new ShowPopupView(this);
        popupView.setOnItemPopupClick(this);
    }

    @OnClick({R.id.id_submit_btn, R.id.id_photo_img})
    public void onClick(View mView) {
        switch (mView.getId()) {
            //图片
            case R.id.id_photo_img:
                popupView.showAtLocPop(mLinearRoot, POPUP_ITEMS);
                break;
            //提交
            case R.id.id_submit_btn:
                if (checkData()) {
                    if (StringUtils.isEmpty(mPhotoFileName)) {
                        ((OilMealPresenter) presenter).mySuggest(mSaveTitle, mSaveContent, "");
                    } else {
                        List<String> mPaths = new ArrayList<String>();
                        mPaths.add(mPhotoFileName);
                        ((OilMealPresenter) presenter).uploadPic(mPaths, null);
                    }
                }
                break;
        }
    }

    private boolean checkData() {
        mSaveTitle = mEditTitle.getText().toString().trim();
        mSaveContent = mEditContent.getText().toString().trim();
        if (StringUtils.isEmpty(mSaveTitle)) {
            SVProgressHUD.showInfoWithStatus(aty, "请输入标题");
        } else {
            if (StringUtils.isEmpty(mSaveContent)) {
                SVProgressHUD.showInfoWithStatus(aty, "请输入内容");
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.HEADPIC_UP_SUCCESS)) {
                //图片上传成功
                List<UploadPicManager.UploadInfo> resultList = (List<UploadPicManager.UploadInfo>) t;
                Message msg = new Message();
                msg.what = 1;
                msg.obj = resultList.get(0).fileSavePath;
                mHandler.sendMessage(msg);
            } else if (TextUtils.equals(tag, ConstantTag.HEADPIC_UP_FAIL)) {
                //图片上传失败
                LogUtils.LogD("图片上传失败", "图片上传失败");
                SVProgressHUD.showInfoWithStatus(aty, "图片上传失败");
            } else if (TextUtils.equals(tag, ConstantTag.SUGGEST_SUCCESS)) {
                //意见上传成功
                SVProgressHUD.showSuccessWithStatus(aty, " 您的意见提交成功，我们会及时处理。");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);
            }
        }
    }

    /**
     * 处理头像的信息
     */
    @Override
    public void OnItemClick(int position, String tag) {
        switch (position) {
            //拍照
            case 0:
                mRecordIndex = 0;
                checkPermissCamer();
                break;
            //系统相册
            case 1:
                mRecordIndex = 1;
                checkPermissCamer();
                break;
        }
    }

    /**
     * 检测用户是否开启权限
     */
    private void checkPermissCamer() {
        String[] perms = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!mayRequestPermission(perms)) {
            return;
        }
        toPhotoGraph();
    }

    @Override
    public void requestPermissionResult(boolean allowPermission) {
        if (allowPermission) {
            toPhotoGraph();
        }
    }

    /**
     * 处理拍照，系统相册
     */
    private void toPhotoGraph() {
        if (mRecordIndex == 0) {
            //拍照
            // 应该先判断SD卡是否存在
            String SDState = Environment.getExternalStorageState();
            if (SDState.equals(Environment.MEDIA_MOUNTED)) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                initHeadPicPath();
                // 下面这句指定调用相机拍照后的照片存储的路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));
                startActivityForResult(intent, IntentCode.General.REQUEST_CODE_TAKE_PICTURE);// 使用手机进行拍照的请求码是：1
            } else {
                SVProgressHUD.showInfoWithStatus(aty, getString(R.string.personal_no_sd_card));
            }
        } else {
            //相册
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            /**
             * 下面这句话，与其它方式写是一样的效果，如果：
             * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
             * intent.setType(""image/*");设置数据类型
             * 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
             */
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    "image/*");
            startActivityForResult(intent, IntentCode.General.REQUEST_CODE_TAKE_ALBUM);// 从相册中取图片的请求码是：2
        }
    }

    private void initHeadPicPath() {
        // 创建拍摄照片保存的文件夹及图片文件名
        String imgName = StringUtils.getPhotoFileName();
        File f = new File(CacheUtils.getCacheDirectory(aty, true, "pic") + imgName);
        if (f.exists()) {
            f.delete();
        }
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (f != null) {
            mPhotoFileName = f.getAbsolutePath();
        }
        mPhotoFile = f;
    }

    /**
     * oss上传图片
     *
     * @param filePath
     */
    public void setHeadImage(String filePath) {
        mPhotoFileName = filePath;
        ImageUtils.showImg(aty, filePath, R.drawable.ic_default_photo, R.drawable.ic_default_photo, mImgPic);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                // 已经选择了照片，这个是通过手机相机拍照返回的请求码
                case IntentCode.General.REQUEST_CODE_TAKE_PICTURE:
                    if (!TextUtils.isEmpty(mPhotoFileName)) {
                        setHeadImage(mPhotoFileName);
                    }
                    break;
                // 相册请求码
                case IntentCode.General.REQUEST_CODE_TAKE_ALBUM:
                    if (null != data) {
                        String path = ImageUtils.getAlbum(aty, data);
                        if (!StringUtils.isEmpty(path)) {
                            setHeadImage(path);
                        } else {
                            SVProgressHUD.showInfoWithStatus(aty, "图片路径错误");
                        }
                    }
                    break;
            }
        }
    }

}
